import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../components/Home'
import SituationAwareness from '../components/SituationAwareness'
import UserManagement from '../components/UserManagement'
import Login from '../components/Login'
import Register from '../components/Register'
import Visualization from '../components/Visualization'
import LogScanHost from '../components/LogScanHost'
//引入Vue-cookies
import VueCookies from 'vue-cookies'

Vue.use(VueRouter)
Vue.use(VueCookies)

const routes = [
  {path: "/",redirect: "/login"},
  {path: "/login",component: Login},
  {path: "/register",component: Register},
  {path: "/home", component: Home,
    // 默认显示这个页面
    redirect:'/situationAwareness',
    children:[
      {path:"/situationAwareness",component: SituationAwareness},
      {path:"/userManagement",component: UserManagement},
      {path:"/visualization",component: Visualization},
      {path:"/logScanHost",component: LogScanHost},
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载前置路由导航守卫
router.beforeEach((to, from, next) => {
  // to 要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  
  // 如果用户访问的是登录或注册页面，直接放行
  if (to.path === '/login' || to.path === '/register')  return next();

  // 状态码不为2，强制跳转到登录页面
  if (VueCookies.get("loginStatus") != 2) {
    return next("/login");
  }
  // 已登录标记不存在但是为登录状态才触发
  if (!VueCookies.isKey("status") && VueCookies.get("loginStatus") == 2) {
    Vue.prototype.$message({
      message: "登录已超时，请重新登陆！",
      type: 'warning'
    });
    // 销毁登录信息的cookie
    VueCookies.remove("loginInfo");
    return next("/login");
  }
  
  // 走到这里就放行了
  next();
})

export default router
